package com.mysite.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mysite.po.User;
import com.mysite.service.UserService;

@Controller
public class IndexController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public ModelAndView enterHelloPage(User u) {

		ModelAndView mv = new ModelAndView();

		boolean result = userService.doLogin(u);

		if (result) {
			mv.setViewName("index");
			
			ModelMap map = mv.getModelMap();
			
			map.addAttribute("current_user", u.getUsername());
	
		} else {
			mv.setViewName("error");
		}

		return mv;
	}

	@RequestMapping(value = "/users", method = RequestMethod.GET)
	@ResponseBody
	public List<User> users(String searchText) {
		return userService.getUsers(searchText);
	}
	
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	@ResponseBody
	public boolean addUser(User user) {
		return userService.addUser(user);
	}
	
	@RequestMapping(value = "/delUser", method = RequestMethod.POST)
	@ResponseBody
	public boolean delUser(int id) {
		return userService.delUser(id);
	}
}
